package com.saas.datasource.core;

import com.saas.datasource.core.annotation.DataSourceAnnotation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * 数据源注解切面实现
 */
@Aspect
@Component
public class DynamicDataSourceAspect {
	private final Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class);
	@Before("@annotation(dataSourceAnnotation)")
	public void before(JoinPoint point, DataSourceAnnotation dataSourceAnnotation) {
		MethodSignature signature = (MethodSignature) point.getSignature();
		try {
			Method method = signature.getMethod();
			if (method.isAnnotationPresent(DataSourceAnnotation.class)) {
				// 取出对应的注解
				String name = "";
				Annotation[][] parameterAnnotations = method.getParameterAnnotations();
				A: for (Annotation[] annotations : parameterAnnotations) {
					for (Annotation annotation : annotations) {
						//获取注解名
						name = annotation.annotationType().getSimpleName();
//						logger.info("######getParameterAnnotations#######"+name);
						if (name.equals("DSParam")){
							break A;
						}
					}
				}
				Object[] param=point.getArgs();
				if(name.equals("DSParam")){
					DynamicDataSourceContextHolder.setDataSource((String) param[0]);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@After("@annotation(dataSourceAnnotation))")
	public void after(JoinPoint point,DataSourceAnnotation dataSourceAnnotation) {
		DynamicDataSourceContextHolder.setDefaultDataSource();
	}

}
